<template>
  <div class="gva-form-box">
    <div class="grid grid-cols-12 w-full gap-2">
      <div class="col-span-3 h-full">
        <div class="w-full h-full bg-white dark:bg-slate-900 px-4 py-8 rounded-lg shadow-lg box-border">
          <div class="user-card px-6 text-center bg-white dark:bg-slate-900 shrink-0">
            <div class="flex justify-center">
              <SelectImage
                v-model="userStore.userInfo.headerImg"
                file-type="image"
              />
            </div>
            <div class="py-6 text-center">
              <p
                v-if="!editFlag"
                class="text-3xl flex justify-center items-center gap-4"
              >
                {{ userStore.userInfo.nickName }}
                <el-icon
                  class="cursor-pointer text-sm"
                  color="#66b1ff"
                  @click="openEdit"
                >
                  <edit />
                </el-icon>
              </p>
              <p
                v-if="editFlag"
                class="flex justify-center items-center gap-4"
              >
                <el-input v-model="nickName" />
                <el-icon
                  class="cursor-pointer"
                  color="#67c23a"
                  @click="enterEdit"
                >
                  <check />
                </el-icon>
                <el-icon
                  class="cursor-pointer"
                  color="#f23c3c"
                  @click="closeEdit"
                >
                  <close />
                </el-icon>
              </p>
              <p class="text-gray-500 mt-2 text-md">这个家伙很懒，什么都没有留下</p>
            </div>
            <div class="w-full h-full text-left">
              <ul class="inline-block h-full w-full">
                <li class="info-list">
                  用户类别:{{ userStore.userInfo.authority.authorityName }}
                </li>

                <li class="info-list">
                  DID:{{ userStore.userInfo.userName }}
                </li>

                <li class="info-list">
                  用户来源:{{ userStore.userInfo.UserSource }}
                </li>


              </ul>

            </div>
          </div>
        </div>
      </div>
      <div class="col-span-9 ">
        <div class="bg-white dark:bg-slate-900 h-full px-4 py-8 rounded-lg shadow-lg box-border">
          <el-tabs
            v-model="activeName"
            @tab-click="handleClick"
          >
            <el-tab-pane
              label="用户信息"
              name="second"
            >
              <ul>
                <li class="borderd">
                  <p class="pb-2.5 text-xl text-gray-600">手机</p>
                  <p class="pb-2.5 text-lg text-gray-400">
                    已绑定手机:{{ userStore.userInfo.phone }}
                    <a
                      href="javascript:void(0)"
                      class="float-right text-blue-400"
                      @click="changePhoneFlag = true"
                    >立即修改</a>
                  </p>
                </li>
                <li class="borderd pt-2.5">
                  <p class="pb-2.5 text-xl text-gray-600">邮箱</p>
                  <p class="pb-2.5 text-lg text-gray-400">
                    已绑定邮箱：{{ userStore.userInfo.email }}
                    <a
                      href="javascript:void(0)"
                      class="float-right text-blue-400"
                      @click="changeEmailFlag = true"
                    >立即修改</a>
                  </p>
                </li>
                <li class="borderd pt-2.5">
                  <p class="pb-2.5 text-xl text-gray-600">修改密码</p>
                  <p class="pb-2.5 text-lg text-gray-400">
                    修改个人密码
                    <a
                      href="javascript:void(0)"
                      class="float-right text-blue-400"
                      @click="showPassword = true"
                    >立即修改</a>
                  </p>
                </li>
                <li class="borderd pt-2.5">
                  <p class="pb-2.5 text-xl text-gray-600">建立日期</p>
                  <p class="pb-2.5 text-lg text-gray-400">
                    {{ userStore.userInfo.CreatedAt }}

                  </p>
                </li>
                <li class="borderd pt-2.5">
                  <p class="pb-2.5 text-xl text-gray-600">余额</p>
                  <p class="pb-2.5 text-lg text-gray-400">
                    {{ userStore.userInfo.balance }}
                    <a
                        href="javascript:void(0)"
                        class="float-right text-blue-400"
                        @click="goToaddmoney"
                    >充值</a>

                  </p>
                </li>

              </ul>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>

    <el-dialog
      v-model="showPassword"
      title="修改密码"
      width="360px"
      @close="clearPassword"
    >
      <el-form
        ref="modifyPwdForm"
        :model="pwdModify"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item
          :minlength="6"
          label="原密码"
          prop="password"
        >
          <el-input
            v-model="pwdModify.password"
            show-password
          />
        </el-form-item>
        <el-form-item
          :minlength="6"
          label="新密码"
          prop="newPassword"
        >
          <el-input
            v-model="pwdModify.newPassword"
            show-password
          />
        </el-form-item>
        <el-form-item
          :minlength="6"
          label="确认密码"
          prop="confirmPassword"
        >
          <el-input
            v-model="pwdModify.confirmPassword"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button

            @click="showPassword = false"
          >取 消</el-button>
          <el-button

            type="primary"
            @click="savePassword"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="changePhoneFlag"
      title="绑定手机"
      width="600px"
    >
      <el-form :model="phoneForm">
        <el-form-item
          label="手机号"
          label-width="120px"
        >
          <el-input
            v-model="phoneForm.phone"
            placeholder="请输入手机号"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="验证码"
          label-width="120px"
        >
          <div class="flex w-full gap-4">
            <el-input
              v-model="phoneForm.code"
              class="flex-1"
              autocomplete="off"
              placeholder="请自行设计短信服务，此处为模拟随便写"
              style="width:300px"
            />
            <el-button
              type="primary"
              :disabled="time>0"
              @click="getCode"
            >{{ time>0?`(${time}s)后重新获取`:'获取验证码' }}</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button

            @click="closeChangePhone"
          >取消</el-button>
          <el-button
            type="primary"

            @click="changePhone"
          >更改</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="changeEmailFlag"
      title="绑定邮箱"
      width="600px"
    >
      <el-form :model="emailForm">
        <el-form-item
          label="邮箱"
          label-width="120px"
        >
          <el-input
            v-model="emailForm.email"
            placeholder="请输入邮箱"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="验证码"
          label-width="120px"
        >
          <div class="flex w-full gap-4">
            <el-input
              v-model="emailForm.code"
              class="flex-1"
              placeholder="请自行设计邮件服务，此处为模拟随便写"
              autocomplete="off"
              style="width:300px"
            />
            <el-button
              type="primary"
              :disabled="emailTime>0"
              @click="getEmailCode"
            >{{ emailTime>0?`(${emailTime}s)后重新获取`:'获取验证码' }}</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button

            @click="closeChangeEmail"
          >取消</el-button>
          <el-button
            type="primary"

            @click="changeEmail"
          >更改</el-button>
        </span>
      </template>
    </el-dialog>
    <div>
      <div>
        <div class="table-wrapper">
          <h2 class="sticky-title">账户管理</h2>
          <div class="gva-btn-list">
          </div>
          <el-table
              :data="upgradeInfoData"
              @sort-change="sortChange"
              @selection-change="handleSelectionChange"
              class="sticky-header-table"
              height="300"
          >
            <el-table-column align="left" label="用户账号" min-width="80" prop="userAccount" sortable="custom" />
            <el-table-column align="left" label="密码" min-width="150" prop="password" sortable="custom" />
            <el-table-column align="left" label="来源应用" min-width="150" prop="source" sortable="custom" />
            <el-table-column align="left" label="创建时间" min-width="150" prop="createTime" sortable="custom" />
            <el-table-column align="left" fixed="right" label="操作" width="200">
              <template>
                <el-button icon="edit" type="primary" link @click="editApiFunc(scope.row)">编辑</el-button>
              </template>
              <template >
                <el-button icon="edit" type="primary" link @click="editApiFunc(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="gva-pagination">
          <el-pagination
              :current-page="page"
              :page-size="pageSize"
              :page-sizes="[10, 30, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
          />
        </div>
      </div>
    </div>

    <div>
      <div>
        <div class="table-wrapper">
          <h2 class="sticky-title">用户公私钥证书信息</h2>
          <div class="gva-btn-list">
            <el-button type="primary" icon="plus" @click="addService()">新增</el-button>
          </div>
          <el-table
              :data="certList"
              @sort-change="sortChange"
              @selection-change="handleSelectionChange"
              class="sticky-header-table"
              height="300"
          >

            <el-table-column
                align="left"
                label="公钥"
                min-width="200"
                prop="Public"
                sortable="custom"
            >
              <template #default="scope">
                <el-tooltip
                    effect="dark"
                    :content="scope.row.Public"
                    v-if="scope.row.Public.length > 50"
                >
                  <span>{{ scope.row.Public.slice(0, 50) }}...</span>
                </el-tooltip>
                <span v-else>{{ scope.row.Public }}</span>
              </template>
            </el-table-column>
            <el-table-column align="left" label="算法类型" min-width="150" prop="Algo" sortable="custom" />
          </el-table>
        </div>
        <div class="gva-pagination">
          <el-pagination
              :current-page="page"
              :page-size="pageSize"
              :page-sizes="[10, 30, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
          />
          <el-drawer v-model="detailDialogS" size="60%" :show-close="false" :close-on-press-escape="false" :close-on-click-modal="false">
            <template #header>
              <div class="flex justify-between items-center">
                <span class="text-lg">证书详情</span>
                <div>
                  <el-button @click="closeDetailDialog">取消</el-button>

                  <el-button type="primary" @click="getaddCert">保存</el-button>
                  <el-button type="primary" @click="getgenerateCert">生成</el-button>
                </div>
              </div>
            </template>

            <el-form ref="detailForm" :rules="rules" :model="serviceInfo" label-width="120px">
              <el-form-item label="公钥" prop="publicKey">
                <el-input v-model="serviceInfo.publicKey" />
              </el-form-item>
              <el-form-item label="私钥" prop="privateKey">
                <el-input v-model="serviceInfo.privateKey" />
              </el-form-item>
              <el-form-item label="算法类型" prop="algo">
              <el-input v-model="serviceInfo.algo" />
            </el-form-item>
              <el-form-item label="存储密码" prop="StoreKey">
                <el-input v-model="serviceInfo.StoreKey" />
              </el-form-item>
            </el-form>
          </el-drawer>
        </div>
      </div>
    </div>
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 py-2">
      <div class="flex flex-col">
        <gva-card custom-class="flex-1">
          <gva-chart :type="12" title="数据量" :dataNumber="dataNumber.value" />
        </gva-card>
      </div>
      <div class="flex flex-col">
        <gva-card custom-class="flex-1">
          <gva-chart :type="13" title="PDC空间" :PDC="PDC.value"/>
        </gva-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router';
import { setSelfInfo, changePassword } from '@/api/user.js'
import { userTotal ,userAccountList ,userCertList,addCert,generateCert} from '@/api/individualUser.js'
import { reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/pinia/modules/user'
import SelectImage from '@/components/selectImage/selectImage.vue'
import {GvaChart,  GvaCard  } from "./componenst"
import {updateApp} from "@/api/application";
defineOptions({
  name: 'userInfo',
})

const activeName = ref('second')
const rules = reactive({
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '最少6个字符', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '最少6个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    { min: 6, message: '最少6个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdModify.value.newPassword) {
          callback(new Error('两次密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
})

const certList=ref([])
const PDC=ref([])
const detailDialogS=ref(false)
const upgradeInfoData=ref([])
const dataNumber=ref([])
const userStore = useUserStore()
console.log('userStore：',userStore.userInfo)
const modifyPwdForm = ref(null)
const showPassword = ref(false)
const pwdModify = ref({})
const nickName = ref('')
const editFlag = ref(false)
const serviceInfo = ref({
  publicKey:'',
  privateKey:'',
  StoreKey:'',
  algo: 1,
})
const savePassword = async() => {
  modifyPwdForm.value.validate((valid) => {
    if (valid) {
      changePassword({
        password: pwdModify.value.password,
        newPassword: pwdModify.value.newPassword,
      }).then((res) => {
        if (res.code === 0) {
          ElMessage.success('修改密码成功！')
        }
        showPassword.value = false
      })
    } else {
      return false
    }
  })
}
const router = useRouter()


const getaddCert = async () => {
  try {

    const userStore = useUserStore();
    console.log('Token:', userStore.token);

    // 调用 API 添加服务
    console.log(serviceInfo.value);
    await addCert(serviceInfo.value);

    ElMessage.success('证书添加成功');
    closeDetailDialog();
    await getTableData(); // 刷新表格数据
  } catch (error) {
    console.error('添加失败', error);
    ElMessage.error('添加失败');
  }
};

const getgenerateCert = async () => {
  try {

    const userStore = useUserStore();
    console.log('Token:', userStore.token);

    // 调用 API 添加服务
    console.log(serviceInfo.value);
    await generateCert(serviceInfo.value);

    ElMessage.success('证书添加成功');
    closeDetailDialog();
    await getuserCertList(); // 刷新表格数据
  } catch (error) {
    console.error('添加失败', error);
    ElMessage.error('添加失败');
  }
};

const getTableData = async () => {
  try {
    await upgradeInfoDataS(); // 调用获取表格数据的函数
  } catch (error) {
    console.error('获取表格数据失败', error);
  }
};



const clearPassword = () => {
  pwdModify.value = {
    password: '',
    newPassword: '',
    confirmPassword: '',
  }
  modifyPwdForm.value.clearValidate()
}

watch(() => userStore.userInfo.headerImg, async(val) => {
  const res = await setSelfInfo({ headerImg: val })
  if (res.code === 0) {
    userStore.ResetUserInfo({ headerImg: val })
    ElMessage({
      type: 'success',
      message: '设置成功',
    })
  }
})

const openEdit = () => {
  nickName.value = userStore.userInfo.nickName
  editFlag.value = true
}

const closeEdit = () => {
  nickName.value = ''
  editFlag.value = false
}

const addService = () => {
  detailDialogS.value = true
}
const closeDetailDialog = () => {
  detailDialogS.value = false
}


const enterEdit = async() => {
  const res = await setSelfInfo({
    nickName: nickName.value
  })
  if (res.code === 0) {
    userStore.ResetUserInfo({ nickName: nickName.value })
    ElMessage({
      type: 'success',
      message: '设置成功',
    })
  }
  nickName.value = ''
  editFlag.value = false
}

const handleClick = (tab, event) => {
  console.log(tab, event)
}

const changePhoneFlag = ref(false)
const time = ref(0)
const phoneForm = reactive({
  phone: '',
  code: ''
})

const getCode = async() => {
  time.value = 60
  let timer = setInterval(() => {
    time.value--
    if (time.value <= 0) {
      clearInterval(timer)
      timer = null
    }
  }, 1000)
}

const closeChangePhone = () => {
  changePhoneFlag.value = false
  phoneForm.phone = ''
  phoneForm.code = ''
}

const changePhone = async() => {
  const res = await setSelfInfo({ phone: phoneForm.phone })
  if (res.code === 0) {
    ElMessage.success('修改成功')
    userStore.ResetUserInfo({ phone: phoneForm.phone })
    closeChangePhone()
  }
}

const changeEmailFlag = ref(false)
const emailTime = ref(0)
const emailForm = reactive({
  email: '',
  code: ''
})

const getEmailCode = async() => {
  emailTime.value = 60
  let timer = setInterval(() => {
    emailTime.value--
    if (emailTime.value <= 0) {
      clearInterval(timer)
      timer = null
    }
  }, 1000)
}

const closeChangeEmail = () => {
  changeEmailFlag.value = false
  emailForm.email = ''
  emailForm.code = ''
}

const changeEmail = async() => {
  const res = await setSelfInfo({ email: emailForm.email })
  if (res.code === 0) {
    ElMessage.success('修改成功')
    userStore.ResetUserInfo({ email: emailForm.email })
    closeChangeEmail()
  }
}

const upgradeInfoDataS = async() => {
  try {
    const response = await userAccountList()
    console.log('用户账户:', response.data) // 打印 API 响应
    if (response.data) {
      const data = response.data
      // 更新数据
      upgradeInfoData.value=response.data.list
    } else {
      console.error('Error fetching data:', response.data)
    }
  } catch (error) {
    console.error('Failed to fetch data:', error)
  }
}

upgradeInfoDataS()

const getuserCertList = async() => {
  try {
    const response = await userCertList()

    if (response.data) {
      certList.value = response.data.list
    } else {
      console.error('Error fetching data:', response.data)
    }
  } catch (error) {
    console.error('Failed to fetch data:', error)
  }
}

getuserCertList()

const getuserTotal = async() => {
  try {
    const response = await userTotal()

    if (response.data) {
      const data = response.data
      PDC.value=data.PDC
      dataNumber.value=data.dataAmount
      console.log("dataNumber:",dataNumber.value)
      console.log("PDC:",PDC.value)
    } else {
      console.error('Error fetching data:', response.data)
    }
  } catch (error) {
    console.error('Failed to fetch data:', error)
  }
}

getuserTotal()
// 去充值
const goToaddmoney = async () => {
  console.log("11")
  router.push({ name: 'addmoney' })
};

</script>

<style lang="scss">
.borderd {
  @apply border-b-2 border-solid border-gray-100 dark:border-gray-500 border-t-0 border-r-0 border-l-0;
    &:last-child{
      @apply border-b-0;
    }
 }

.info-list{
  @apply w-full whitespace-nowrap overflow-hidden text-ellipsis py-3 text-lg text-gray-700
}

</style>
